package com.wz.dhs.config.idwork;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 分布式ID(基于redis)
 */
@Slf4j
public class IdWorkerConfig {

    private static final Integer DATA_SIZE = 32;
    private static final String[] RADIX_STR = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v"};
    private static Map<String, Integer> RADIX_MAP = new LinkedHashMap<>();

    private static final String DATA_CENTER_PREFIX = "gyp:center:%s";

    static {
        for (int i = 0; i < DATA_SIZE; i++) {
            RADIX_MAP.put(RADIX_STR[i], i);
        }
    }


    public static HashMap<String, Integer> calculateDataIdAndWorkId2(String appName, RedisConnectionFactory connectionFactory) {
        String key = String.format(DATA_CENTER_PREFIX, appName);
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, connectionFactory);
        Long num = redisAtomicLong.incrementAndGet();
        //result在0~1023之间
        long result = num % (DATA_SIZE * DATA_SIZE);
        //将result转化为32进制数，个位为worlId，十位为dataId
        String strResult = Integer.toString(Math.toIntExact(result), DATA_SIZE);
        String strResult2 = StringUtils.leftPad(strResult, 2, "0");
        String substring1 = strResult2.substring(0, 1);
        String substring2 = strResult2.substring(1, 2);
        Integer dataId = RADIX_MAP.get(substring1);
        Integer workId = RADIX_MAP.get(substring2);
        HashMap<String, Integer> workMap = new HashMap<>();
        workMap.put("workId", workId);
        workMap.put("dataId", dataId);
        return workMap;
    }

    public static void main(String[] args) {
         //   String key = String.format(RedisKeyConstant.USER_TOKEN_PREFIX, appName);
//            Long num = RedisUtils.generateNum(key);
            //result在0~1023之间
            long result = 1023;
            //将result转化为32进制数，个位为worlId，十位为dataId
            String strResult = Integer.toString(Math.toIntExact(result), DATA_SIZE);
            String strResult2 = StringUtils.leftPad(strResult, 2, "0");
            String substring1 = strResult2.substring(0, 1);
            String substring2 = strResult2.substring(1, 2);
            Integer dataId = RADIX_MAP.get(substring1);
            Integer workId = RADIX_MAP.get(substring2);
            HashMap<String, String> workMap = new HashMap<>();
            workMap.put("workId", String.valueOf(workId));
            workMap.put("dataId", String.valueOf(dataId));
    }

}
